package com.njupt.HashTable;

import java.awt.*;
import java.util.*;
import java.util.stream.Stream;

/**
 * 349. 两个数组的交集
 */
public class Intersection {

    /**
     * 暴力法
     * @param nums1
     * @param nums2
     * @return
     */
    public int[] intersection(int[] nums1, int[] nums2) {

        ArrayList<Integer> integers = new ArrayList<>();
        int len1 = nums1.length;
        int len2 = nums2.length;
        if(len1<=len2){
            for (int i = 0; i < len1; i++) {
               if(isInArray(nums1[i],nums2) && !integers.contains(nums1[i])) {
                   integers.add(nums1[i]);
               }
            }
        }else {
            for (int i = 0; i < len2; i++) {
               if( isInArray(nums2[i],nums1) && !integers.contains(nums2[i])){
                   integers.add(nums2[i]);
               }
            }
        }
        int[] result = new int[integers.size()];
        for (int i = 0; i < integers.size(); i++) {
            result[i] = integers.get(i);
        }
        return result;

    }

    public boolean isInArray(int num,int[] nums){
        for (int i = 0; i < nums.length; i++) {
            if(nums[i] == num){
                return true;
            }
        }
        return false;
    }

    /**
     * 使用数组的哈希法
     * @param nums1
     * @param nums2
     * @return
     */
    public int[] intersection2(int[] nums1, int[] nums2) {
        int[] temp = new int[1001];
        Set<Integer> setRes = new HashSet();
        for(int i = 0;i < nums1.length; i++){
            temp[nums1[i]] = 1;
        }
        for(int i = 0;i < nums2.length; i++){
            if(temp[nums2[i]] == 1){
                setRes.add(nums2[i]);
            }
        }
        return setRes.stream().mapToInt(s -> s).toArray();
    }

    /**
     * 使用集合的哈希法
     * @param nums1
     * @param nums2
     * @return
     */
    public int[] intersection3(int[] nums1, int[] nums2) {
        Set<Integer> set = new HashSet<>();
        Set<Integer> result = new HashSet<>();

        for (int i = 0; i < nums1.length; i++) {
            set.add(nums1[i]);
        }

        for (int i = 0; i < nums2.length; i++) {
            if(set.contains(nums2[i])){
                result.add(nums2[i]);
            }
        }

        return result.stream().mapToInt(num->num).toArray();
    }
    public static void main(String[] args) {

        Intersection test = new Intersection();

        int[] nums1 = {1,2,2,1};
        int[] nums2 = {2,2};
        int[] result = test.intersection3(nums1, nums2);
        System.out.println(Arrays.toString(result));

    }
}
